package com.mdlib.helper.module.send.profile.fragments;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ljlib.core.util.FileUtils;
import com.ljlib.core.util.common.StringUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.MDUploadPic;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.event.ImageID;
import com.mdlib.helper.event.SelectEvent;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.entity.SelectEntity;
import com.mdlib.helper.model.entity.UserEntity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.GlideCircleTransform;
import com.mdlib.helper.utils.ImageUtils;
import com.mdlib.helper.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 作者：HQY on 16/11/15 17:15
 * 邮箱：hqy_xz@126.com
 */

public class ProfileEditFragment extends BaseTitleFragment implements EasyPermissions.PermissionCallbacks {
    private static final int CAPTURE_IMAGE_CAMERA = 100;
    private static final int IMAGE_STORE = 200;
    private static final int CAMERA_PERM = 1;
    public static final int CROP_CHOOSE = 10;
    private static final String PIC = "pic";
    private static final String SEX = "sex";
    @Bind(R.id.iv_profile_head)
    ImageView mIvProfileHead;
    @Bind(R.id.rl_edit_head)
    RelativeLayout mRlEditHead;
    @Bind(R.id.tv_profile_nickname)
    TextView mTvProfileNickname;
    @Bind(R.id.rl_edit_nickname)
    RelativeLayout mRlEditNickname;
    @Bind(R.id.tv_profile_phone)
    TextView mTvProfilePhone;
    @Bind(R.id.rl_edit_phone)
    RelativeLayout mRlEditPhone;
    @Bind(R.id.tv_profile_sex)
    TextView mTvProfileSex;
    @Bind(R.id.rl_edit_sex)
    RelativeLayout mRlEditSex;

    private String[] pics = {"相册", "拍照"};
    private String[] sexs = {"男", "女"};
    private Uri origUri;
    private String protraitPath;
    private File protraitFile;
    private List<SelectEntity> selectList;

    public static ProfileEditFragment newInstance() {
        return new ProfileEditFragment();
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_profile_edit;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setTitle(R.string.profile_material_tv_title, R.color.white)
                .setTitleBgColor(R.color.generic_view_bg)
                .setImgLeftListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeFragment();
                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        selectList = new ArrayList<>();
        getUserInfo();
    }

    private void getPicList() {
        selectList.clear();
        for (int i = 0; i < pics.length; i++) {
            SelectEntity select = new SelectEntity();
            select.setId(i);
            select.setTitle(pics[i]);
            selectList.add(select);
        }
    }

    private void getSexList() {
        selectList.clear();
        for (int i = 0; i < sexs.length; i++) {
            SelectEntity select = new SelectEntity();
            select.setId(i);
            select.setTitle(sexs[i]);
            selectList.add(select);
        }
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo() {
        startLoadingDialog(true);
        addSubscribe(DataManager.getInstance().getUserApi()
                .fetchUserInfo()
                .compose(RxHelper.<BaseResult<UserEntity>>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult<UserEntity>>() {
                    @Override
                    protected void onSucc(BaseResult<UserEntity> userEntity) {
                        stopLoadingDialog();
                        updateUserInfo(userEntity.data);
                    }

                    @Override
                    protected void onFail(String msg) {
                        stopLoadingDialog();
                        ToastUtil.showToast(msg);
                    }
                }));
    }


    public void updateUserInfo(UserEntity user) {
        Glide.with(getActivity())
                .load(user.getAvatarUrl())
                .placeholder(R.drawable.iv_app_default_head)
                .error(R.drawable.iv_app_default_head)
                .transform(new GlideCircleTransform(getActivity()))
                .into(mIvProfileHead);
        mTvProfileNickname.setText(user.getNickName());
        mTvProfilePhone.setText(user.getPhone());
        if (user.getSex().equals("man")) {
            mTvProfileSex.setText(getActivity().getResources().getString(R.string.profile_man));
        } else if (user.getSex().equals("woman")) {
            mTvProfileSex.setText(getActivity().getResources().getString(R.string.profile_woman));
        }
    }

    @OnClick({R.id.rl_edit_head, R.id.rl_edit_nickname, R.id.rl_edit_phone, R.id.rl_edit_sex})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_edit_head:
                getPicList();
                UIHelper.showSelectList(getActivity(), selectList, PIC);
                break;
            case R.id.rl_edit_nickname:
                addFragment(ModifyNameFragment.newInstance(mTvProfileNickname.getText().toString()));
                break;
            case R.id.rl_edit_phone:
                break;
            case R.id.rl_edit_sex:
                getSexList();
                UIHelper.showSelectList(getActivity(), selectList, SEX);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SelectEvent selectEvent) {

        String type = selectEvent.getType();
        if (type.equals(PIC)) {
            if (selectEvent.getSelectEntity().getTitle().equals(pics[0])) {
                startImagePick();
            } else if (selectEvent.getSelectEntity().getTitle().equals(pics[1])) {
                startTakePhotoByPermissions();
            }
        } else if (type.equals(SEX)) {
            if (selectEvent.getSelectEntity().getTitle().equals(sexs[0])) {
                setSex("man");
            } else if (selectEvent.getSelectEntity().getTitle().equals(sexs[1])) {
                setSex("woman");
            }
        }
    }

    private void setSex(String sex) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .setSex(sex)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                        getUserInfo();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case CAPTURE_IMAGE_CAMERA:
                startActionCrop(origUri);
                break;
            case IMAGE_STORE:
                startActionCrop(data.getData());
                break;
            case CROP_CHOOSE:
                getImageId(protraitFile.getPath());
                break;


        }
    }

    private void getImageId(String name) {
        List<String> nameList = new ArrayList<>();
        nameList.add(name);
        MDUploadPic.uploadPic(nameList, getActivity(), "2");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ImageID id) {
        if (id.getIdList().size() < 0) {
            return;
        }
        uploadFace(id.getIdList().get(0));

    }

    /**
     * 修改头像
     *
     * @param imgId
     */
    private void uploadFace(String imgId) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .uploadFace(imgId)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                        getUserInfo();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 拍照后裁剪
     *
     * @param data 原始图片
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 450);
        intent.putExtra("aspectY", 450);
        intent.putExtra("outputX", 450);
        intent.putExtra("outputY", 450);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        getActivity().startActivityForResult(intent,
                CROP_CHOOSE);
    }

    private final static String FILE_SAVEPATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/ZB/Portrait/";

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            ToastUtil.showToast("无法保存上传的头像，请检查SD卡是否挂载");
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getAbsoluteImagePath(getActivity(), uri);
        }
        String ext = FileUtils.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "zb_crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        return Uri.fromFile(protraitFile);
    }

    /**
     * 选择图片
     */

    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            getActivity().startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    IMAGE_STORE);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            getActivity().startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    IMAGE_STORE);
        }
    }

    @AfterPermissionGranted(CAMERA_PERM)
    private void startTakePhotoByPermissions() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this.getContext(), perms)) {
            try {
                startTakePhoto();
            } catch (Exception e) {
                Toast.makeText(this.getContext(), R.string.permissions_camera_error, Toast.LENGTH_LONG).show();
            }
        } else {
            // Request one permission
            EasyPermissions.requestPermissions(this,
                    getResources().getString(R.string.str_request_camera_message),
                    CAMERA_PERM, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        try {
            startTakePhoto();
        } catch (Exception e) {
            Toast.makeText(this.getContext(), R.string.permissions_camera_error, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(this.getContext(), R.string.permissions_camera_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/helper/Camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            ToastUtil.showToast("无法保存照片，请检查SD卡是否挂载");
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = "zb_" + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        origUri = uri;

        String theLarge = savePath + fileName;

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        getActivity().startActivityForResult(intent,
                CAPTURE_IMAGE_CAMERA);
    }

}
